package com.chromatic.competition.service;

import static android.content.Context.MODE_PRIVATE;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.chromatic.competition.inteface.UserInitializationService;
import com.chromatic.competition.model.LoginRequestBody;
import com.chromatic.competition.model.RegisterRequestBody;
import com.chromatic.competition.utils.RetrofitClientUtil;
import com.chromatic.competition.view.account.LoginActivity;
import com.chromatic.competition.view.MainActivity;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UserServiceImpl {
    /**
     * 用户登录
     *
     * @param activity 当前活动
     * @param username 用户名
     * @param password 密码
     */
    public static void login(Activity activity, String username, String password){
        UserInitializationService userInitializationService = RetrofitClientUtil.getInstance().getApiService();
        // 调用登录接口
        LoginRequestBody requestBody = new LoginRequestBody(username, password);
//        System.out.println("输入的用户名：" + username + "输入的密码：" + password);
        Call<Map<String,Object>> loginCall = userInitializationService.loginUser(requestBody);

        loginCall.enqueue(new Callback<Map<String, Object>>() {
            @Override
            public void onResponse(@NonNull Call<Map<String, Object>> call,
                                   @NonNull Response<Map<String, Object>> response) {
                if (response.isSuccessful()) {
                    Map<String, Object> data = response.body();
                    assert data != null;
                    String message = (String)data.get("message");

                    Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();

                    String token = Objects.requireNonNull(data.get("token")).toString();
                    JSONObject currentUser = new JSONObject((Map) Objects.requireNonNull(data.get("user")));
//                    Log.d("ProfileFragment", "获取到的用户信息: " + currentUser);

                    // 保存用户信息和token
                    SharedPreferences sharedPreferences = activity.getSharedPreferences("login_info", MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("user", String.valueOf(currentUser));
                    editor.putString("token", token);
                    editor.apply();
//                    Log.d("ProfileFragment", "已登录的用户信息: " + currentUser);

                    // 登录成功，跳转到主页面
                    Intent intent = new Intent(activity, MainActivity.class);
                    activity.startActivity(intent);
                    activity.finish();
                } else {
                    JSONObject errorBody = null;
                    String errorMessage = null;
                    try {
                        if (response.errorBody() != null) {
                            errorBody = new JSONObject(response.errorBody().string());
                        }
                    } catch (JSONException | IOException e) {
                        throw new RuntimeException(e);
                    }
                    try {
                        if (errorBody != null) {
                            errorMessage = errorBody.getString("message");
                        }
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                    Toast.makeText(activity, "登录失败：" + errorMessage, Toast.LENGTH_SHORT).show();
//                    Log.e("LoginActivity", "登录失败：" + response.code() + errorMessage);
                }
            }
            @Override
            public void onFailure(@NonNull Call<Map<String, Object>> call, @NonNull Throwable t) {
                Toast.makeText(activity,  "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 用户注册
     *
     * @param activity               当前活动
     * @param username               用户名
     * @param phoneNumber            手机号码
     * @param password               密码
     * @param confirmPassword        确认密码
     * @param smsVerificationCode    短信验证码
     */
    public static void register(Activity activity, String username, String phoneNumber,
                                String password, String confirmPassword, String smsVerificationCode) {
//        String invitationCode = invitationCodeEditText.getText().toString().trim();
        if (username.isEmpty() || password.isEmpty() || confirmPassword.isEmpty() ||
                phoneNumber.isEmpty() || smsVerificationCode.isEmpty()) {
            Toast.makeText(activity, "请填写完整的注册信息！", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!password.equals(confirmPassword)) {
            Toast.makeText(activity, "两次密码不一致！", Toast.LENGTH_SHORT).show();
            return;
        }

        UserInitializationService userInitializationService = RetrofitClientUtil.getInstance().getApiService();
        RegisterRequestBody requestBody = new RegisterRequestBody(username,password,phoneNumber,smsVerificationCode);
        Call<JsonObject> registerCall = userInitializationService.registerUser(requestBody);

        registerCall.enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(@NonNull Call<JsonObject> call, @NonNull Response<JsonObject> response) {
                if (response.isSuccessful()) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                    builder.setTitle("提示");
                    builder.setMessage("注册成功！");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss(); // 关闭对话框
                            activity.finish(); // 返回上一个 Activity
                        }
                    });
                    builder.show();

                    // 注册成功，跳转到登录页面
                    Intent intent = new Intent(activity, LoginActivity.class);
                    activity.startActivity(intent);
                    activity.finish();
                }
                if (response.code() == 400) {
                    String errorBodyString  = null;
                    try {
                        assert response.errorBody() != null;
                        errorBodyString = response.errorBody().string();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
//                    System.out.println("响应体内容为：" + errorBodyString);
                    JsonObject errorMessageJson = new Gson().fromJson(errorBodyString, JsonObject.class);
                    String errorMessage = errorMessageJson.get("message").getAsString();

                    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                    builder.setTitle("注册失败");
                    builder.setMessage(errorMessage);
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss(); // 关闭对话框
                        }
                    });
                    AlertDialog dialog = builder.create();
                    dialog.show();
                }
            }
            @Override
            public void onFailure(@NonNull Call<JsonObject> call, @NonNull Throwable t) {
                Toast.makeText(activity, t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}
